Net : Network client and server based on stream

更新时间:
2024-05-13
下载文档

Net : Network client and server based on stream

The net module provides an asynchronous network API for creating stream-based TCP or TLS servers: net.createServer() and clients: net.createConnection().

User can use the following code to import the net module.

var net = require('net');

Support

The following shows net module APIs available for each permissions.

 User ModePrivilege Mode
Socket
net.connect
net.createConnection
socket.address
socket.connect
socket.destroy
socket.end
socket.pause
socket.resume
socket.setKeepAlive
socket.setNoDelay
socket.setTimeout
socket.write
socket.bufferSize
socket.bytesRead
socket.bytesWritten
socket.connecting
socket.destroyed
socket.localAddress
socket.localPort
socket.pending
socket.remoteAddress
socket.remoteFamily
socket.remotePort
socket.timeout
socket.readyState
socket.encrypted
net.createServer
net.createSubServer
server.address
server.listen
server.close
server.isMaster
server.groupName
server.addcert
server.port
net.isIP
net.isIPv4
net.isIPv6

Socket Class

new net.Socket([options])

  • options {Object} Available options are:
    • allowHalfOpen Indicates whether half-opened TCP connections are allowed. See the 'end' event for details. Default: false.

Creates a new socket object.

net.createConnection(options[, connectListener])

  • options {Object} Required. Will be passed to the new net.Socket([options]) method.
    • port {Integer} Port the socket should connect to.
    • host {String} Host the socket should connect to, both ip and host name ware accepted.
    • family {Integer} Version of IP stack. Must be 4, 6. default: 4.
    • tlsOpt {Object} TLS securely connections options. default: undefined, means use TCP connection.
  • connectListener {Function} Common parameter of socket.connect() methods. Will be added as a listener for the connect event once.
  • Returns: {Socket} The newly created socket used to start the connection.

This function creates a new with all options set to default, asynchronously initiates connection with socket.connect(), then returns the net.Socket that starts the connection.

Example

var net = require('net');
var client = net.createConnection({host: '192.168.7.31', port: 3000});

client.on('connect', function () {
  // 'connect' listener.
  console.log('connected to server!');
  client.write('world!\r\n');
});

client.on('data', function (chunk) {
  console.log('recv msg:' + chunk.toString());
  client.end();
});

client.on('end', function () {
  console.log('disconnected from server');
});

net.connect(options)

Aliases to net.createConnection().

Socket Object

Socket object inherits from Duplex class.

socket.address()

  • Returns: {Object} Local sockaddr.

Returns the bound address, the address family name and port of the socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }.

socket.connect(options[, connectListener])

  • options {Object} Available options are:
    • port {Integer} Required. Port the socket should connect to.
    • host {String} Host the socket should connect to. default: localhost.
    • family {Integer} Version of IP stack. Must be 4, 6. default: 4.
    • lookup {Function} Custom lookup function. default: dns.lookup().
  • connectListener {Function} Common parameter of socket.connect() methods. Will be added as a listener for the connect event once.
  • Returns: {net.Socket} The socket itself.

Initiate a connection on a given socket. Normally this method is not needed, the socket should be created and opened with net.createConnection(). Use this only when implementing a custom Socket.

socket.connect(port[, host][, connectListener])

  • port {Number} Port the client should connect to.
  • host {String} Host the client should connect to.
  • connectListener {Function} Common parameter of socket.connect() methods. Will be added as a listener for the connect event once.
  • Returns: {net.Socket} The socket itself.

Initiate a TCP connection on the given socket.

Alias to socket.connect(options[, connectListener]) called with {port: port, host: host} as options.

socket.connect(saddr[, tlsOpt][, connectListener])

  • saddr {Object} Socket address.
  • tlsOpt {Object} TLS securely connections options. default: undefined, means use TCP connection.
  • connectListener {Function} Common parameter of socket.connect() methods. Will be added as a listener for the connect event once.
  • Returns: {net.Socket} The socket itself.

Initiate a connection on a given socket. Normally this method is not needed, the socket should be created and opened with net.createConnection(). Use this only when implementing a custom Socket.

socket.destroy([error])

  • error {Error} Error object.
  • Returns: The socket itself.

Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.

See writable.destroy() for further details.

socket.end([data[, encoding]][, callback])

  • data {String | Buffer} Data to write.
  • encoding {String} Only used when data is string. default: 'utf8'.
  • callback{Function} Optional callback for when the socket is finished.
  • Returns: The socket itself.

Half-closes the socket. It is possible the server will still send some data.

See writable.end() for further details.

socket.pause()

  • Returns: The socket itself.

Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.

socket.resume()

  • Returns: The socket itself.

Resumes reading after a call to socket.pause().

socket.setKeepAlive([enable][, initialDelay])

  • enable {Boolean} Default: false
  • initialDelay {Integer} Default: 0ms
  • Returns: The socket itself.

Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket.

socket.setNoDelay([noDelay])

  • noDelay {Boolean} Default: true
  • Returns: The socket itself.

Enable/disable the use of Nagle's algorithm.

When a TCP connection is created, it will have Nagle's algorithm enabled.

Nagle's algorithm delays data before it is sent via the network. It attempts to optimize throughput at the expense of latency.

Passing true for noDelay or not passing an argument will disable Nagle's algorithm for the socket. Passing false for noDelay will enable Nagle's algorithm.

socket.setTimeout(timeout[, callback])

  • timeout {Integer}
  • callback {Function}
  • Returns: The socket itself.

Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default net.Socket do not have a timeout.

When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed. The user must manually call socket.end() or socket.destroy() to end the connection.

Example

socket.setTimeout(3000);
socket.on('timeout', () => {
  console.log('socket timeout');
  socket.end();
});

If timeout is 0, then the existing idle timeout is disabled.

The optional callback parameter will be added as a one-time listener for the 'timeout' event.

socket.write(data[, encoding][, callback])

  • data {String | Buffer} Data to write.
  • encoding {String} Only used when data is string. default: utf8.
  • callback {Function} Optional callback for when the socket is finished.
  • Returns: {Boolean} Whether this operation was successful.

Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

The optional callback parameter will be executed when the data is finally written out, which may not be immediately.

See Writable stream write() method for more information.

socket.bufferSize

  • {Integer} This property shows the number of characters buffered for writing.

net.Socket has the property that socket.write() always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket. The network connection simply might be too slow. Net will internally queue up the data written to a socket and send it out over the wire when it is possible.

The consequence of this internal buffering is that memory may grow. Users who experience large or growing bufferSize should attempt to "throttle" the data flows in their program withsocket.pause() and socket.resume().

socket.bytesRead

  • {Integer} The amount of received bytes.

socket.bytesWritten

  • {Integer} The amount of bytes sent.

socket.connecting

  • {Boolean} If true, socket.connect() was called and has not yet finished. It will stay true until the socket becomes connected, then it is set to false and the 'connect' event is emitted.

socket.destroyed

  • {Boolean} Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.

See writable.destroyed for further details.

socket.pending

  • {Boolean} This is true if the socket is not connected yet, either because .connect() has not yet been called or because it is still in the process of connecting (see socket.connecting).

socket.localAddress

  • {String} The string representation of the local IP address.

socket.localPort

  • {Integer} The numeric representation of the local port. For example, 80 or 21.

socket.remoteAddress

  • {String} The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).

socket.remoteFamily

  • {String} The string representation of the remote IP family. IPv4 or IPv6.

socket.remotePort

  • {Integer} The numeric representation of the remote port. For example, 80 or 21.

socket.timeout

  • {Integer | undefined} The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set.

socket.readyState

  • {String} This property represents the state of the connection as a string.
    • If the stream is connecting socket.readyState is opening.
    • If the stream is readable and writable, it is open.
    • If the stream is readable and not writable, it is readOnly.
    • If the stream is not readable and writable, it is writeOnly.

socket.encrypted

  • {Boolean} This property represents whether this socket is a TLS secure connection.

This property is valid in EdgerOS 2.1.7 and above.

Socket Events

close

Emitted once the socket is fully closed. The argument hadError is a boolean which says if the socket was closed due to a transmission error.

  • hadError {Boolean} true if the socket had a transmission error.

connect

Emitted when a socket connection is successfully established. See net.createConnection().

data

Emitted when data is received. The argument data will be a Buffer or String.

  • data {Buffer | String} Received data.

The data will be lost if there is no listener when a Socket emits a 'data' event.

drain

Emitted when the write buffer becomes empty. Can be used to throttle uploads.

See also: the return values of socket.write().

end

Emitted when the other end of the socket , thus ending the readable side of the socket.

By default (allowHalfOpen is false) the socket will destroy its file descriptor once it has written out its pending write queue. However, if allowHalfOpen is set to true, the socket will not automatically end() its writable side, allowing the user to write arbitrary amounts of data. The user must call end() explicitly to close the connection.

finish

When the data transmission is completed, this event will be generated.

error

Emitted when an error occurs. The 'close' event will be called directly following this event.

  • err {Error}

ready

Emitted when a socket is ready to be used.

Triggered immediately after 'connect'.

timeout

Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.

See also: socket.setTimeout().

lookup

Emitted after resolving the host name but before connecting.

  • err {Error | null} The error object.
  • address {String} The IP address.
  • family {Integer} The address type. The value muslt be 4 or 6.
  • host {String} The host name.

Server Class

net.createServer(group, subs[, subMode][, saddr[, tlsOpt]])

  • group {String} Server group name(master server module). Usually the module name is used as the group name. If the server work on mult-task mode(subs > 0) and subMode is missing, the group must be supported as app module name.
  • subs {Integer} The new task counts, if subs > 0, server run in mult-task.
  • subMode {String} sub-server module. If the sub-server is the same module as the master-server, subMode can be defaulted and provided by group. Otherwise, subMode represents the sub-server module.
  • saddr {Object} Server socket address. If the port of saddr is set to 0, the setting port will be assigned automatically, and the port can be found through server.port().
  • tlsOpt {Object} TLS securely connections options. default: undefined, means use TCP connection.

This method creates a master-server. When the master-server starts, it can create a specified number(subs) of sub-servers (subs), refer to Server mult-task.

Example

  • Create single server:
var net = require('net');

var saddr = socket.sockaddr(socket.INADDR_ANY, 3000);
var server = net.createServer('server', 0, saddr);

server.listen();
  • Create mult-task server:
var net = require('net');

var saddr = socket.sockaddr(socket.INADDR_ANY, 3000);
var server = net.createServer('./server', 2, saddr);

server.listen();

net.createSubServer(group)

  • group {String} Server group name, the same as master-server group name.

Use this method to create a sub-server when the sub-server is not on the same module as the master-server.

Example

  • Master-server, ./master.js:
var net = require('net');

var saddr = socket.sockaddr(socket.INADDR_ANY, 3000);
server = net.createServer('server', 2, './sub', saddr);

server.listen();
  • Sub-server, ./sub.js:
var net = require('net');

var server = net.createSubServer('server');

server.listen();

Server mult-task

The net.Server have two work mode:

  • MASTER The master-server listens and receives the client connection. If the sub server is registered on the master server, the master server will dispatch the connection to itself or the sub server for processing.

  • SUB The sub-server works on a separate task. It does not listen on the port, does not directly accept connection from the client, but accepts connection dispatched by the master-server.

A net.Server can be a single task or multiple tasks(mult-task). When it works in mult-task mode, there is one master-server and several sub-servers, which are created by master-server when the master-server is started. When the master-server is working, the client connection are evenly distributed to all the sub-servers and the master-server itself.

The sub-server can be the same module as the master-server, or it can be a different module. If they are on the same module, you don't need to create a sub-server explicitly. If the sub-server is not on the same module as master-server, user should create it by net.createSubServer.

Server Object

server.address()

  • Returns: {Object | null}

Returns the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address): { port: 12346, family: 'IPv4', address: '127.0.0.1' }.

server.address() returns null before the 'listening' event has been emitted or after calling server.close().

server.listen([callback])

  • callback {function} When the server starts listening, the 'listening' event will be emitted. The parameter callback will be added as a listener for the 'listening' event.

Start server. If listen operation fail, an error will been throwed.

server.close([callback])

  • callback {function} Called when the server is closed.

Stop server.

server.isMaster()

  • Returns: {Boolean} Whether it is the master server.

Get whether the server object is the master server.

server.groupName

  • groupName {Object}
    • group {String} The server grpup name, see Server mult-task.
    • name {String} The server name, see Server mult-task.

server.addcert(opt)

  • opt {Object} Tls server option.
  • Returns: {Boolean} Whether it was added successfully.

opt includes following items:

  • name {String} Server domain name.
  • ca {String} Optional trusted CA certificates. default: no CA certificates.
  • cert {String} Server certificate.
  • key {String} Private key of server certificate.
  • passwd {String} Private key password. default: no password.

This method adds a SNI (Server Name Indication) certificate to the tls server. SNI is an extension used to improve SSL or TLS for servers. It mainly solves the disadvantage that one server can only use one certificate (one domain name). With the support of the server for virtual hosts, one server can provide services for multiple domain names, so SNI must be supported to meet the demand.

server.port()

  • Returns: {Integer | Undefined} Server socket port.

When the server starts with the MASTER module, server.port() gets the port of the server, otherwise it returns undefined.

Example

var port = server.port();
console.log(port);

net.isIP(input)

  • input {String} Input string.
  • Returns: {Integer} The IP version of string.

Test whether the input is an IP address. Invalid string returns 0, IPv4 address returns 4, and IPv6 address returns 6.

net.isIPv4(input)

  • input {String} Input string.
  • Returns: {Boolean} Whether input string is IPv4 string.

It returns true if the input is an IPv4 address, otherwise it returns false.

net.isIPv6(input)

  • input {String} Input string.
  • Returns: {Boolean} Whether input string is IPv6 string.

It returns true if the input is an IPv6 address, otherwise it returns false.

Server Events

listening

Emitted when the server start done. It has the following properties:

  • server {net.Server} The net.Server object self.

close

Emitted when the http server stop. It has the following properties:

  • server {net.Server} The net.Server object self.

connection

Emitted when a client connection comes to server. It has the following properties:

  • connect {net.Socket} The net.Socket object, see net.Socket.

Example

  • client:
var iosched = require('iosched');
var net = require('net');

var client = net.createConnection({ host: '192.168.7.31', port: 3000 });

var timer = undefined;
var count = 0;
function setTimer(enable = true) {
  if (enable && !timer) {
    timer = setInterval(
      () => {
        client.write(`Send msg(${count++})`);
    }, 1000);
  } else if (!enable && timer) {
    clearInterval(timer);
    timer = undefined;
  }
}

function done() {
  setTimer(false);
}

client.on('connect', function () {
  console.log('client connect.');
  setTimer();
});

client.on('data', function (chunk) {
  console.log('recv msg:' + chunk.toString());
});

client.on('error', function (err) {
  console.log('client error');
  done();
});

client.on('close', function (err) {
  console.log('client close');
  done();
});

while (true) {
  iosched.poll();
}
  • server:
var iosched = require('iosched');
var net = require('net');
var socket = require('socket');

var saddr = socket.sockaddr(socket.INADDR_ANY, 3000);
var server = net.createServer('net', 0, saddr);

server.on('connection', (connect) => {
  console.log(`connect (${connect.id}) open.`);

  connect.on('data', (buf) => {
    console.log('rece msg:' + buf.toString());
    connect.write(buf);
  });

  connect.on('close', () => {
    console.log(`connect(${connect.id}) close.`);
  });
});

server.listen();

while (true) {
  iosched.poll();
}
文档内容是否对您有所帮助?
有帮助
没帮助